@extends("layout.app")

@section("page-content")
    <div class="container mx-auto py-8 px-4 sm:px-6 lg:px-8 max-w-4xl">
        <!-- Event Details -->
        <div class="bg-white p-6 rounded-lg shadow-md mb-6">
            <h1 class="text-3xl font-bold text-gray-800 mb-2">{{$event->title}}</h1>
            <p class="text-gray-700 mb-4">{{$event->title ?? ''}}</p>
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <p class="text-gray-600">Category: <span class="font-semibold">{{$event->category->name}}</span></p>
                <p class="text-gray-600">Type: <span class="font-semibold">{{$event->type}}</span></p>
                <p class="text-gray-600">Created by: <span class="font-semibold">{{$event->creator->name}} ({{$event->creator->email}})</span></p>
                <p class="text-gray-600">Time: <span class="font-semibold">{{$event->start_at}} - {{$event->end_at}}</span></p>
            </div>
            @can("join-event",$event)
            <div class="mt-4 flex flex-col sm:flex-row space-y-2 sm:space-y-0 sm:space-x-4">
                <button class="join-btn bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600">Join</button>
            </div>
            @endcan
        </div>

        <!-- Creator Section (Admin only) -->
        <div class="bg-white p-6 rounded-lg shadow-md mb-6">
            <p class="joined-names text-lg font-semibold text-gray-800 mb-2">Joined: {{implode(', ',$event->participants()->pluck("name")->toArray())}}</p>
            @can('invite-attendee',$event)
            <button id="invite-btn" class="bg-green-500 text-white px-4 py-2 rounded hover:bg-green-600 mb-2">Invite</button>
            @endcan
            <div id="invite-form" class="hidden mt-2 p-4 bg-gray-100 rounded relative">
                <input id="user-search" class="w-full p-2 border rounded mb-2" placeholder="Search users..." autocomplete="off">
                <div id="user-dropdown" class="absolute left-0 right-0 bg-white border rounded shadow-md max-h-40 overflow-y-auto hidden">
                    @foreach($users as $user)
                    <div class="p-2 hover:bg-gray-100 cursor-pointer" ondblclick="addToInvited(this)">{{$user->name}} ({{$user->email}})</div>
                    @endforeach
                </div>
{{--                <button id="send-invites" class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 mt-2 w-full sm:w-auto">Send Invites</button>--}}
            </div>
            <p class="text-lg font-semibold text-gray-800 mt-2">Invited: <span id="invited-list" class="flex flex-wrap gap-2">
                @foreach($event->invitations as $inv)
                    <span class="invited-user bg-gray-200 px-2 py-1 rounded flex items-center">
                    {{$inv->user->name}} <span class="ml-2 text-red-500 cursor-pointer" onclick="removeInvited(this)">x</span>
                </span>
                    @endforeach
            </span></p>
        </div>

        <!-- Comments Section -->
        <div class="bg-white p-6 rounded-lg shadow-md">
            @if(Auth::check())
            <h2 class="text-2xl font-bold text-gray-800 mb-4">Comments</h2>
            <form class="mb-6">
                <textarea class="w-full p-2 border rounded resize-none" rows="3" placeholder="Write your comment..."></textarea>
                <button type="submit" class="mt-2 bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 w-full sm:w-auto">Submit</button>
            </form>
            @endif
            <div class="space-y-4">
                <div class="border-b pb-4">
                    <p class="text-gray-800">Great event!</p>
                    <p class="text-sm text-gray-500">By User2 on 2025-03-05 12:00</p>
                    <a href="#" onclick="showReply(event, 'id1')" class="text-blue-500 hover:underline">Reply</a>
                    <div id="id1" class="reply hidden mt-2">
                        <textarea class="w-full p-2 border rounded resize-none" rows="2" placeholder="Write your reply..."></textarea>
                        <div class="mt-2 flex flex-col sm:flex-row space-y-2 sm:space-y-0 sm:space-x-2">
                            <button class="btn-ok bg-blue-500 text-white px-4 py-1 rounded hover:bg-blue-600">Submit</button>
                            <button class="btn-cancel bg-red-500 text-white px-4 py-1 rounded hover:bg-red-600">Cancel</button>
                        </div>
                    </div>
                    <div class="ml-0 sm:ml-6 mt-2">
                        <p class="text-gray-800">Thanks!</p>
                        <p class="text-sm text-gray-500">By User3 on 2025-03-05 12:30</p>
                        <a href="#" onclick="showReply(event, 'id2')" class="text-blue-500 hover:underline">Reply</a>
                        <div id="id2" class="reply hidden mt-2">
                            <textarea class="w-full p-2 border rounded resize-none" rows="2" placeholder="Write your reply..."></textarea>
                            <div class="mt-2 flex flex-col sm:flex-row space-y-2 sm:space-y-0 sm:space-x-2">
                                <button class="btn-ok bg-blue-500 text-white px-4 py-1 rounded hover:bg-blue-600">Submit</button>
                                <button class="btn-cancel bg-red-500 text-white px-4 py-1 rounded hover:bg-red-600">Cancel</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection
@section("script")
    <script>
        const searchInput = document.getElementById('user-search');
        const dropdown = document.getElementById('user-dropdown');
        document.getElementById('invite-btn')?.addEventListener('click', (e) => {
            e.preventDefault();
            document.getElementById('invite-form').classList.toggle('hidden');
        });

        searchInput.addEventListener('keyup', async function() {
            if (this.value.length > 0)
            {
                const response = await fetch(`http://127.0.0.1:8000/search-users?name=${this.value}&event_id={{$event->id}}`)
                const data = await response.json()
                Array.from(dropdown.children).forEach(el=>el.remove())
                data.users.forEach(user=>{
                    dropdown.innerHTML += (`<div class="p-2 hover:bg-gray-100 cursor-pointer" ondblclick="addToInvited(this)">${user.name} (${user.email})</div>`)

                })
                dropdown.classList.remove('hidden');
            }
            else {
                dropdown.classList.add('hidden');
            }
        });

        async function addToInvited(element) {
            const selectedUser = element.textContent;
            const invitedList = document.getElementById('invited-list');
            const currentInvited = Array.from(invitedList.children).map(span => span.textContent.replace('x', '').trim());
            if (!currentInvited.includes(selectedUser)) {
                //Add to the database through API
                const response = await
                fetch('/invitations', {
                    method: 'POST',
                    // include 跨域请求带上 cookie, 默认是：same-origin, 不跨域默认带上
                    // credentials: 'include',
                    headers: {
                        "Content-type": "application/json",
                        "X-CSRF-TOKEN": "{{ csrf_token() }}"
                    },
                    body: JSON.stringify({
                        'event_id': 1,
                        'user_id': 3
                    })
                });
                if(response.status===200){
                    const userSpan = document.createElement('span');
                    userSpan.className = 'invited-user bg-gray-200 px-2 py-1 rounded flex items-center';
                    userSpan.innerHTML = `${selectedUser} <span class="ml-2 text-red-500 cursor-pointer" onclick="removeInvited(this)">x</span>`;
                    invitedList.appendChild(userSpan);

                    searchInput.value = '';
                    dropdown.classList.add('hidden');
                }

            }

        }

        function removeInvited(element) {
            // Remove from the database through API
            element.parentElement.remove();
        }

        document.addEventListener('click', (e) => {
            if (!e.target.closest('#invite-form')) dropdown.classList.add('hidden');
        });

        function showReply(e, id) {
            e.preventDefault();
            document.querySelectorAll('.reply').forEach(el => el.classList.add('hidden'));
            document.querySelectorAll('.btn-ok, .btn-cancel').forEach(el => {
                el.addEventListener('click', e => e.target.closest('.reply').classList.add('hidden'));
            });
            document.getElementById(id).classList.remove('hidden');
        }

        $(".join-btn")?.addEventListener("click",async e=>{
            const response = await fetch("http://127.0.0.1:8000/join-event?event_id={{$event->id}}");
            const data = await response.json()
            if(response.status===200){
                $(".joined-names").textContent += ", "+data.name
                e.target.classList.add("hidden")
            }
        })

    </script>
@endsection
